<?php

/**
 * Class to represent a service error. Returned by StorageServiceClient when there is some error.
 *
 */
class Ext_Error
{
    // Esto es usado para identificar un error despues de encodear/decodearlo json 
    const Ext_Error_IDENTITY = 'Ext_Error_IDENTITY';
    // Posibles errores
    const ERROR_UNDEFINED = 0x00000000;
    const ERROR_STORAGE_FULL = 0x00000001;
    const ERROR_SOAP = 0x10000000;

    public $identity;
    public $error;
    public $errorType;

    /**
     * Default constructor.
     *
     * @param  mixed error message
     */
    public function __construct( $error, $errorType = self::ERROR_UNDEFINED )
    {
        $this->identity = self::Ext_Error_IDENTITY;
        $this->error = $error;
        $this->errorType = $errorType;
    }

    /**
     * Tell whether a value is an error. 
     *
     * @param   mixed $data     the value to test
     * @return  bool            true if parameter is an error
     */
    public static function isError( &$data )
    {
        if ( is_soap_fault( $data ) ) {
            $data = new Ext_Error( 'Soap Error: ' . $data->faultstring, self::ERROR_SOAP );
            return true;
        }
        if ( is_array( $data ) && isset( $data[ 'error' ] ) && $data[ 'identity' ] === self::Ext_Error_IDENTITY ) {
            $data = new Ext_Error( $data[ 'error' ], isset($data['errorType'])?$data['errorType']:self::ERROR_UNDEFINED );
            return true;
        }
        if ( $data instanceof stdClass ) {
            if ( isset( $data->identity ) && $data->identity === self::Ext_Error_IDENTITY ) {
                $data = new Ext_Error( $data->error, isset($data->errorType)?$data->errorType:self::ERROR_UNDEFINED );
                return true;
            }
        }
        return $data instanceof Ext_Error;
    }

    /**
     * Get the error message from an error object.
     *
     * @return string error message
     */
    public function getMessage()
    {
        if ( is_soap_fault( $this->error ) ) {
            return 'Soap Error: ' . $this->error->faultstring;
        }
        if ( is_array( $this->error ) ) {
            $ret = " ";
            foreach ( $this->error as $t => $err ) {
                $ret .= $t . " " . $err . " ";
            }
            return $ret;
        }
        if ( $this->error instanceof stdClass ) {
            $ret = " ";
            foreach ( get_object_vars( $this->error ) as $t => $err ) {
                $ret .= $t . " " . $err . " ";
            }
            return $ret;
        }
        return strval( $this->error );
    }

    /**
     * Get the error message errorType .
     *
     * @return error errorType
     */
    public function getType()
    {
        return $this->errorType;
    }

    // }}}
    // {{{ toString()
    function __toString()
    {
        return $this->getMessage();
    }
    // }}}
// {{{ toString()
}


